package com.hspedu.bot.service.impl.user.account;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hspedu.bot.pojo.User;
import com.hspedu.bot.service.user.UserService;
import com.hspedu.bot.service.user.account.RegisterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

@Service
public class RegisterServiceImpl implements RegisterService {

    @Autowired
    private UserService userService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public Map<String, String> register(String username, String password, String confirmedPassword) {
        //去除首尾空格
        username = username.trim();

        //判断
        Map<String, String> map = new HashMap<>();
        if (!StringUtils.hasText(username)) {
            map.put("error_message", "用户名不能为空");
            return map;
        }
        if (!StringUtils.hasText(password) || !StringUtils.hasText(confirmedPassword)) {
            map.put("error_message", "密码不能为空");
            return map;
        }

        //判断长度
        if (username.length() > 100) {
            map.put("error_message", "用户名不能大于100");
            return map;
        }
        if (password.length() > 100 || confirmedPassword.length() > 100) {
            map.put("error_message", "密码长度不能大于100");
            return map;
        }

        //密码不一样
        if (!password.equals(confirmedPassword)) {
            map.put("error_message", "两次密码内容不相同");
            return map;
        }

        //查询用户名是否重复
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        User one = userService.getOne(queryWrapper);
        if (one != null) {
            map.put("error_message", "用户名重复");
            return map;
        }

        //将用户放入数据库中
        String encodePassword = passwordEncoder.encode(password);
        Integer score = 1000;
        String photo = "https://cdn.acwing.com/media/user/profile/photo/45850_lg_8badd3ae7e.jpg";
        userService.save(new User(null, username, encodePassword, photo, 1500));

        map.put("error_message", "success");
        return map;
    }
}
